import 'dart:async';
import 'dart:io';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';
import 'package:notification_centre/notification_centre.dart';

class JcPurchase {
  late StreamSubscription<List<PurchaseDetails>> _subscription;
  late InAppPurchase _inAppPurchase;
  List<ProductDetails> _products = []; //内购的商品对象集合

  //初始化购买组件
  initializeInAppPurchase() {
    // 初始化in_app_purchase插件
    _inAppPurchase = InAppPurchase.instance;

    //监听购买的事件
    final Stream<List<PurchaseDetails>> purchaseUpdated =
        _inAppPurchase.purchaseStream;
    _subscription = purchaseUpdated.listen((purchaseDetailsList) {
      _listenPurchaseUpdated(purchaseDetailsList);
    }, onDone: () {
      _subscription.cancel();
      _loadingDisMiss(msg: "Cancel Buy");
    }, onError: (error) {
      error.printError();
      _loadingDisMiss(msg: "Buy Fail");
    });
  }

  /// 购买准备
  buyProduct(String productId, String orderNo) async {
    print("请求商品id $productId");

    List<String> outProducts = [productId];

    final bool available = await _inAppPurchase.isAvailable();
    if (!available) {
      _loadingDisMiss(msg: 'AppPurchase Not Available');
      return;
    }

    //查询商品
    List<String> kIds = outProducts;

    final ProductDetailsResponse response =
        await _inAppPurchase.queryProductDetails(kIds.toSet());
    print("商品查询结果  ${response.productDetails}");
    if (response.notFoundIDs.isNotEmpty) {
      _loadingDisMiss(msg: 'No Product');
      return;
    }

    // 处理查询到的商品列表
    List<ProductDetails> products = response.productDetails;
    print("products ==== ${products.length}");
    if (products.isNotEmpty) {
      //赋值内购商品集合
      _products = products;
    }

    print("全部商品加载完成了，可以启动购买了,总共商品数量为：${products.length}");
    //结束上一次购买
    var paymentWrapper = SKPaymentQueueWrapper();
    var transactions = await paymentWrapper.transactions();
    print("  initStoreInfo transaction.length${transactions.length}");
    for (SKPaymentTransactionWrapper item in transactions) {
      print(
          "wztest  initStoreInfo transaction==>${item.transactionIdentifier}");
      await paymentWrapper.finishTransaction(item);
    }

    _startPurchase(productId, orderNo);
  }

  // 开始购买
  _startPurchase(String productId, String orderNo) async {
    if (_products.isNotEmpty) {
      // ToastUtil.showToast("准备开始启动购买流程");
      try {
        ProductDetails productDetails = _getProduct(productId);

        print(
            "一切正常，开始购买,信息如下：title: ${productDetails.title}  desc:${productDetails.description} "
            "price:${productDetails.price}  currencyCode:${productDetails.currencyCode}  currencySymbol:${productDetails.currencySymbol}");
        _inAppPurchase.buyConsumable(
            purchaseParam: PurchaseParam(
                productDetails: productDetails,
                applicationUserName: '$orderNo$productId'));
      } catch (e) {
        print(e.toString());
        _loadingDisMiss(msg: 'Buy Fail');
      }
    } else {}
  }

  // 根据产品ID获取产品信息
  ProductDetails _getProduct(String productId) {
    return _products.firstWhere((product) => product.id == productId);
  }

  /// 内购的购买更新监听
  _listenPurchaseUpdated(List<PurchaseDetails> purchaseDetailsList) async {
    for (PurchaseDetails purchase in purchaseDetailsList) {
      if (purchase.status == PurchaseStatus.pending) {
        // 等待支付完成
        _handlePending();
      } else if (purchase.status == PurchaseStatus.canceled) {
        // 取消支付
        _handleCancel(purchase);
      } else if (purchase.status == PurchaseStatus.error) {
        // 购买失败
        _handleError(purchase.error!);
      } else if (purchase.status == PurchaseStatus.purchased ||
          purchase.status == PurchaseStatus.restored) {
        //完成购买, 到服务器验证
        if (Platform.isAndroid) {
        } else if (Platform.isIOS) {
          var appstoreDetail = purchase as AppStorePurchaseDetails;
          _checkApplePayInfo(appstoreDetail);
        }
      }
    }
  }

  /// 购买失败
  _handleError(IAPError iapError) {
    
    _loadingDisMiss(msg: iapError.message);
  }

  /// 等待支付
  _handlePending() {
    print('支付中------');
  }

  /// 取消支付
  _handleCancel(PurchaseDetails purchase) {
    _inAppPurchase.completePurchase(purchase);
    _loadingDisMiss(msg: "Cancel Buy");
  }

  //   /// Android支付成功的校验
  // void checkAndroidPayInfo(GooglePlayPurchaseDetails googleDetail) async {
  //   _inAppPurchase.completePurchase(googleDetail);
  //   print("安卓支付交易ID为${googleDetail.purchaseID}");
  //   print("安卓支付验证收据为${googleDetail.verificationData.serverVerificationData}");
  // }

  /// Apple支付成功的校验
  _checkApplePayInfo(AppStorePurchaseDetails appstoreDetail) async {
    _inAppPurchase.completePurchase(appstoreDetail);

    print("Apple支付交易ID为${appstoreDetail.purchaseID}");
    print(
        "Apple支付验证收据为${appstoreDetail.verificationData.serverVerificationData}");
    _loadingDisMiss(msg: 'Buy Successful', isSuccess: true);
    NotificationCenter().postNotification('appPurchaseSuccess', data: {
      'transactionId': appstoreDetail.purchaseID,
      'payload': appstoreDetail.verificationData.serverVerificationData
    });
  }

  onClose() {
    if (Platform.isIOS) {
      final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition =
          _inAppPurchase
              .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      iosPlatformAddition.setDelegate(null);
    }
    _subscription.cancel();
  }

  resumePurchase() {
    _inAppPurchase.restorePurchases();
  }

  _loadingDisMiss({String msg = '', bool isSuccess = false}) {
    EasyLoading.dismiss();
    if (isSuccess) {
      EasyLoading.showSuccess(msg);
    } else {
      EasyLoading.showError(msg);
    }
  }
}
